package com.asset.inventory.utils

import com.asset.inventory.constant.ConfigPath
import com.asset.inventory.kt.logE
import java.io.*

/**
 * 页面名称：文件读写
 * 创建时间  2021/04/18 22:29
 */
object FileUtils {
    private const val TAG = "FileUtils"
    /**
     * 读取Sdcard文件内容
     * @param context
     * @param filePathAndName 文件完整的路径，包含文件名，如"/sdcard/file.txt
     */
    fun getContentFromSdcard(): String? {
        val filePathAndName = ConfigPath.offlineFilePath
        "getContentFromSdcard filePathAndName: $filePathAndName".logE()
        try {
            val fr = FileReader(filePathAndName)
            var bufReader: BufferedReader? = null
            try {
                if (null == fr) {
                    return null
                }
                bufReader = BufferedReader(fr)
                var result = ""
                var line: String? = bufReader.readLine()
                while (line != null) {
                    result += line
                    line = bufReader.readLine()
                }
                "getContentFromSdcard result: $result".logE()
                return result
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                closeSilently(fr)
                closeSilently(bufReader)
            }
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        }

        return null
    }

    /**
     * 向指定文件写入指定内容
     */
    fun write2File(str: String) {
        val fw = FileWriter(ConfigPath.offlineFilePath)
        try {
            "getContentFromSdcard startWrite: ".logE()
            fw.write(str)
            "getContentFromSdcard endWrite: ".logE()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            closeSilently(fw)
        }
    }

    fun closeSilently(closeable: Closeable?){
        if (closeable != null) {
            try {
                closeable.close()
            } catch (e: java.lang.Exception) {
            }
        }
    }
}